import React, { useEffect, useRef, useState } from "react";
import loginBack from "../../assets/images/login-back.webp";
import { Form, Input, Button, message as antdMessage } from "antd";
import { LoginRawState } from "../../types";
// 注意 该插件需要独立下载类型声明文件
// npm install qrcode @types/qrcode
import QRCode from "qrcode";
import { login } from "../../api";
import { useNavigate } from "react-router-dom";

const Index: React.FC = () => {
  // 获取hooks 
  const navigate = useNavigate()
  // 状态变量
  const [isCodeLogin, setIsCodeLogin] = useState(false);
  // 二维码路径
  const [url, setUrl] = useState("")
  // 登录函数
  const handleFinish = async (value: LoginRawState) => {
    // console.log(value);
    // 1. 实现登录--发送请求
    const resp =  await login(value);
    // 2. 根据返回结果给出友好提示
    const { code, message, data } = resp.data;
    // 3. code 判断
    if(code === 200) {
      // 提示
      antdMessage.success(message);
      // 跳转页面
      navigate('/')
      // 存储用户信息
      localStorage.setItem('avator', data.avator)
      localStorage.setItem('id', data.id)
      localStorage.setItem('nickname', data.nickname)
      localStorage.setItem('tel', data.tel)
      localStorage.setItem('email', data.email)
      localStorage.setItem('token', data.token)
      localStorage.setItem('role', data.role)

      // redux 
    } else {
      // 提示
      antdMessage.error(message)
    }
  };

  // 副作用
  useEffect(() => {
    // 创建二维码
    QRCode.toDataURL("二维码内容").then((url) => {
      setUrl(url);
    });
  }, []);
  return (
    <div style={{ backgroundImage: `url(${loginBack})` }} className="login">
      <div className="login-box">
      <div className="text" onClick={() => setIsCodeLogin(!isCodeLogin)}>{ isCodeLogin ? '切换账号密码登录' : "切换二维码登录" }</div>

        {!isCodeLogin ? (
          <Form
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            onFinish={(value) => handleFinish(value)}
          >
            <Form.Item wrapperCol={{ span: 24 }}>
              <h2 style={{ textAlign: "center" }}>用户登录</h2>
            </Form.Item>
            <Form.Item
              label="用户名"
              name="username"
              rules={[
                {
                  required: true,
                  message: "用户名不可以为空！！！",
                },
                {
                  pattern: /^(1[3-9]\d{9})|(\w+@\w+\.(com|cn|net))$/,
                  message: "用户名必须是手机号或者邮箱",
                },
              ]}
            >
              <Input placeholder="请输入手机号或邮箱"></Input>
            </Form.Item>
            <Form.Item
              label="密码"
              name="password"
              rules={[
                {
                  required: true,
                  message: "密码不可以为空！！！",
                },
                {
                  pattern: /^\w{6,12}$/,
                  message: "密码必须由6-12数字、字母、下划线组成",
                },
              ]}
            >
              <Input.Password placeholder="请输入6到12数字、字母、下划线密码"></Input.Password>
            </Form.Item>
            <Form.Item wrapperCol={{ span: 20, offset: 4 }}>
              <Button type="primary" block htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        ) : (
          <div className="code">
            <h3>微信扫一扫登录</h3>
            <img src={url} alt="" width={200} height={200} />
          </div>
        )}
      </div>
    </div>
  );
};

export default Index;
